<template>
  <div class="app-container" :class="pageIndex" v-loading="dataLoading">
    <van-nav-bar :title="scaleItem.scaleName" left-arrow @click-left="$router.back()" />
    <div class="content-box">
      <template v-if="pageIndex == 'index'">
        <div class="title-box">
          <div class="tip">{{ '标准化心理评估系统\n10道题定位你的心理行为坐标' }}</div>
          <div class="title">{{ scaleItem.scaleName }}</div>
        </div>
        <div class="introduce-box">
          <div class="title">职业锚测评</div>
          <div class="content">{{ scaleItem.description }}</div>
        </div>
        <div class="handle-btn" @click="startExam">开始测评</div>
      </template>
      <template v-if="pageIndex == 'exam'">
        <div class="question-box">
          <div class="question-title">
            <div class="title">{{ optionTypeObj[currentExam.optionType] }}</div>
            <div class="num">{{ `${currentExamIndex + 1} / ${examTotal}` }}</div>
          </div>
          <div class="content">
            <el-form ref="examFormRef" class="exam-form" :model="examForm" :rules="examFormRules" label-position="top">
              <el-form-item :label="currentExam.questionText" :prop="`question${currentExam.questionId}`">
                <!-- 单选题 -->
                <el-radio-group v-if="currentExam.optionType == 'radio'"
                  v-model="examForm[`question${currentExam.questionId}`]">
                  <el-radio v-for="option in currentExam.scalesOptionsList" :key="option.optionText"
                    :label="option.options">
                    {{ option.optionText }}
                  </el-radio>
                </el-radio-group>
                <!-- 多选题 -->
                <el-checkbox-group v-if="currentExam.optionType == 'checkbox'"
                  v-model="examForm[`question${currentExam.questionId}`]">
                  <el-checkbox v-for="option in currentExam.scalesOptionsList" :key="option.optionText"
                    :label="option.options">
                    {{ option.optionText }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="handle-btn" v-if="examList.length == currentExamIndex + 1" @click="examSubmit">获取我的评估</div>
        <div class="handle-btn-box" v-else>
          <div class="handle-btn" @click="preQuestion">上一题</div>
          <div class="handle-btn" @click="nextQuestion">下一题</div>
        </div>
      </template>
      <template v-if="pageIndex == 'result'">
        <div class="result-box">
          <el-scrollbar>
            <div class="text-box">
              <div class="tip-box">{{ '测试完成啦!\n请获取您的专属推荐' }}</div>
              <div class="result-text">
                <div class="result">
                  <div class="main-result">
                    {{`根据您的回答\n推测您${examResult.result == '正常' ? '一切正常' : `患有${examResult.result}焦虑`}~`}}</div>
                </div>
                <div class="tip">
                  <div class="other-result">{{ examResult.recommendations }}</div>
                  <div class="text">
                    {{ examResult.result == '正常' ? '您可以选择观看我们的推荐的视频了解更多心理知识' : '不要担心，您可以选择进行更深的试题分析，或者观看我们的推荐的视频进行焦虑缓解~'
                  }}
                  </div>
                </div>
              </div>
            </div>
            <div class="list-box column2">
              <div class="list-title-box">
                <div class="list-title">视频推荐</div>
                <div class="tip">如有需要也可以拨打我们的员工心理热线</div>
              </div>
              <div class="list-content" v-if="videoList.length">
                <el-scrollbar>
                  <div class="list-item" v-for="(item, index) in videoList" :key="index" @click="showVideoDialog(item)">
                    <div class="item-cover">
                      <svg-icon icon-class="play-fill" />
                      <img class="cover-img" :src="item.cover">
                    </div>
                    <div class="item-label">{{ item.fileName }}</div>
                  </div>
                </el-scrollbar>
              </div>
              <div class="empty" v-else v-loading="videoListLoading">暂无数据</div>
            </div>
            <div class="list-box column" v-if="examResult.result != '正常'">
              <div class="list-title">更深测试</div>
              <div class="list-content" v-if="deepExamList.length">
                <el-scrollbar>
                  <div class="list-item" v-for="(item, index) in deepExamList" :key="index" @click="toExam(item)">
                    <img class="item-cover" :src="require(`@/assets/images/mindStation/${'scaleType2.png'}`)">
                    <div class="item-label-box">
                      <div class="item-label">{{ item.scaleName }}</div>
                      <div class="item-tip">{{ item.description }}</div>
                    </div>
                  </div>
                </el-scrollbar>
              </div>
              <div class="empty" v-else>暂无数据</div>
            </div>
          </el-scrollbar>
        </div>
      </template>
    </div>
    <!-- 视频弹窗 -->
    <VideoDialog :visible.sync="videoDialogVisible" :params="videoDialogParams" />
  </div>
</template>

<script>
import * as api from '@/api/mindStation/index.js';
import VideoDialog from '@/views/mindStation/components/VideoDialog.vue';
import { getVideoBase64 } from '@/utils/index.js';

export default {
  name: 'ExamTest',
  components: { VideoDialog },
  data() {
    return {
      dataLoading: false,
      pageIndex: 'index',
      scaleItem: null,
      examForm: {},
      examList: [],
      examTotal: 0,
      currentExamIndex: 0,
      currentExam: {},
      optionTypeObj: {
        radio: '单选题',
        checkbox: '多选题',
      },
      checkList: [],
      examResult: {},
      videoListLoading: false,
      videoList: [],
      videoDialogVisible: false,
      videoDialogParams: {},
      deepExamList: [],
    };
  },
  computed: {
    examFormRules() {
      return {
        [`question${this.currentExam.questionId}`]: [{ required: true, message: '请进行答题', trigger: 'blur' }],
      };
    },
  },
  created() {
    if (this.$route.query.scaleItem) this.scaleItem = JSON.parse(this.$route.query.scaleItem);
  },
  mounted() {
    this.getData();
  },
  methods: {
    getData() {
      console.log('getData');
      this.dataLoading = true;
      // 获取题目
      if (this.$route.query.pageIndex == 'exam') {
        api.selectQuestionsWithOptionsByScaleId({ scaleId: this.scaleItem.scaleId }).then((res) => {
          this.examList = res.rows;
          this.examList.forEach((exam) => {
            if (exam.optionType == 'radio') this.$set(this.examForm, `question${exam.questionId}`, '');
            if (exam.optionType == 'checkbox') this.$set(this.examForm, `question${exam.questionId}`, []);
          });
          this.examTotal = res.total;
          this.dataLoading = false;
        });
      }
      // 获取题目记录
      if (this.$route.query.pageIndex == 'result') {
        this.pageIndex = this.$route.query.pageIndex;
        api.recordsList({ scaleId: this.scaleItem.scaleId }).then((res) => {
          this.examResult = res.rows[res.rows.length - 1];
          // 已经答过题，直接返回结果
          if (this.examResult) {
            this.getVideoList();
            if (this.examResult.result != '正常') this.getDeepExamList();
            this.pageIndex = 'result';
            this.dataLoading = false;
            return;
          }
        });
      }
    },
    startExam() {
      this.pageIndex = 'exam';
      this.currentExamIndex = 0;
      this.currentExam = this.examList[0];
    },
    preQuestion() {
      this.currentExamIndex -= 1;
      this.currentExam = this.examList[this.currentExamIndex];
    },
    nextQuestion() {
      this.$refs.examFormRef.validate((valid) => {
        if (!valid) return;
        this.currentExamIndex += 1;
        this.currentExam = this.examList[this.currentExamIndex];
      });
    },
    // 题目提交
    examSubmit() {
      this.$refs.examFormRef.validate((valid) => {
        if (!valid) return;
        this.pageIndex = 'result';
        const list = [];
        const score = this.examList.reduce((pre, item) => {
          if (item.optionType == 'checkbox') {
            let score = 0;
            if (this.scaleItem.scaleId == 3) {
              if (item.questionId == 26) {
                score = 0;
                if ([3, 4].includes(this.examForm[`question${item.questionId}`].length)) score = 1;
                if ([5, 6].includes(this.examForm[`question${item.questionId}`].length)) score = 2;
                if (this.examForm[`question${item.questionId}`].length >= 7) score = 3;
              }
              if (item.questionId == 28) {
                score = 1;
                if (this.examForm[`question${item.questionId}`].includes('A')) score = 0;
                if (this.examForm[`question${item.questionId}`].includes('B')) score = 2;
                if (this.examForm[`question${item.questionId}`].includes('D')) score = 2;
              }
            }
            const checkedOptionList = item.scalesOptionsList.filter((option) =>
              this.examForm[`question${item.questionId}`].includes(option.options)
            );
            list.push({
              scaleId: item.scaleId,
              optionId: checkedOptionList.map((option) => option.optionId).join(','),
              questionId: item.questionId,
              options: checkedOptionList.map((option) => option.options).join(','),
              score,
            });
            return (pre += score);
          } else {
            const checkedOption = item.scalesOptionsList.find(
              (option) => option.options == this.examForm[`question${item.questionId}`]
            );
            const { optionId, questionId, options, score } = checkedOption;
            list.push({ scaleId: item.scaleId, optionId, questionId, options, score });
            return (pre += checkedOption.score);
          }
        }, 0);
        const param = { scaleId: this.scaleItem.scaleId, score, list };
        api.addRecordsAndAnswers(param).then(() => {
          api.recordsList({ scaleId: this.scaleItem.scaleId }).then((res) => {
            this.examResult = res.rows[res.rows.length - 1];
            if (this.examResult.result != '正常') this.getDeepExamList();
          });
          this.getVideoList();
        });
      });
    },
    getVideoList() {
      this.videoListLoading = true;
      api.videoListRandom({ videoType: 1 }).then(async (res) => {
        await res.rows.reduce(async (pre, item) => {
          await pre;
          return getVideoBase64(item.filePath).then((res) => {
            item.cover = res;
          });
        }, Promise.resolve());
        this.videoList = res.rows;
        this.videoListLoading = false;
      });
    },
    showVideoDialog(item) {
      this.videoDialogVisible = true;
      this.videoDialogParams = { src: item.filePath };
    },
    getDeepExamList() {
      api.scalesList({ scaleId: this.examResult.showScaleId }).then((res) => {
        this.deepExamList = res.rows;
      });
    },
    toExam(item) {
      this.$router.replace({ name: 'ExamTest', query: { scaleItem: JSON.stringify(item), pageIndex: 'exam' } });
      this.$router.go(0);
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@/assets/styles/mixin.scss';

.app-container {
  // width: calc(100% - 40px);
  // height: calc(100% - 40px);
  // padding: 20px;
  background-color: #425afe;
  background-image: url('~@/assets/images/examTest/index_BG.png');
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-position: top;
  background-size: 100%;

  &.exam,
  &.result {
    background-image: url('~@/assets/images/examTest/other_BG.png'), linear-gradient(180deg, #425afe 0%, #7f8fff 100%);
  }

  // display: flex;
  // flex-direction: column;
  .content-box {
    width: calc(100% - 40px);
    height: calc(100% - 70px);
    padding: 10px 20px;
    display: flex;
    flex-direction: column;
  }
}

::v-deep .van-nav-bar {
  &::after {
    content: none;
  }

  .van-icon {
    color: #fff !important;
  }

  .van-nav-bar__title {
    color: #cfeafe;
  }
}

.title-box {
  flex-shrink: 0;
  width: 100%;
  aspect-ratio: 9.7 / 10;
  display: flex;
  flex-direction: column;
  justify-content: center;

  .tip,
  .title {
    color: #fff;
    font-weight: bold;
  }

  .tip {
    width: 70%;
    // margin-top: 14%;
    font-size: 18px;
    white-space: pre-wrap;
  }

  .title {
    width: 100%;
    margin-top: 10%;
    font-size: 36px;
  }
}

.introduce-box {
  flex: 1;
  width: 100%;

  .title {
    padding: 15px;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    background-image: linear-gradient(90deg, #7075f8 0%, #94b5fc 100%);
    color: #fff;
    font-size: 20px;
    font-weight: bold;
  }

  .content {
    padding: 15px;
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
    background-color: #fff;
  }
}

.question-box {
  margin-top: 10px;
  margin-bottom: 20px;
  padding: 15px;
  border-radius: 10px;
  background-color: #fff;
  // display: flex;
  // flex-direction: column;
  // align-items: start;

  .question-title {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      width: auto;
      padding: 10px 20px;
      border-radius: 10px;
      background-image: linear-gradient(270deg, #70bbf8 2%, #9afb7f 100%);
      color: #fff;
      font-size: 16px;
      font-weight: bold;
    }

    .num {
      color: #425afe;
      font-size: 14px;
    }
  }

  .content {
    width: 100%;

    ::v-deep .el-form {
      // .el-form-item {
      //   margin: 0;
      // }
      .el-form-item__label {
        line-height: normal;
        padding: 15px 0;
        color: #3d3d3d;
        font-size: 16px;
      }

      .el-radio-group {
        width: 100%;
      }

      .el-radio {
        display: block;
        border-radius: 6px;
        background: #eeeeee;
        padding: 10px 15px;
        margin-right: 0;
        margin-bottom: 15px;

        &:last-child {
          margin-bottom: 0;
        }

        &.is-checked {
          background: #dde2ff;

          .el-radio__label {
            color: #425afe !important;
          }
        }
      }
    }
  }
}

.result-box {
  display: flex;
  flex-direction: column;
  align-items: start;
  overflow: auto;

  // ::v-deep .el-scrollbar__view {
  //   display: flex;
  //   flex-direction: column;
  //   align-items: start;
  // }

  .text-box {
    background-image: url('~@/assets/images/examTest/result_BG.png');
    background-repeat: no-repeat;
    background-position: top right;
    background-size: 154px 222px;

    .tip-box {
      width: 50%;
      border-radius: 10px;
      padding: 10px;
      margin-bottom: 20px;
      background-color: #fff;
      font-size: 18px;
      color: #445cfe;
      white-space: pre-wrap;
    }

    .result-text {
      .result {
        line-height: 1.8;
        white-space: pre-wrap;
        .main-result {
          font-size: 22px;
          color: #fff;
        }
        .other-result {
          font-size: 16px;
          color: #fff;
        }
      }

      .tip {
        .other-result {
          padding: 10px;
          border-radius: 10px;
          background-image: linear-gradient(270deg, #70bbf8 2%, #7ad461 100%);
          color: #fff;
          font-weight: bold;
          margin-bottom: 10px;
        }
        margin-top: 15px;
        line-height: 1.8;
        // font-size: 18px;
        // color: #efefef;
        font-size: 16px;
        background: #fff;
        border-radius: 10px;
        padding: 10px 15px;
      }
    }
  }

  @include list-box-style;

  .list-box {
    width: calc(100% - 30px);
    // min-height: 350px;
    margin-top: 20px;
    align-items: start;
    .list-title-box {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: end;
      margin-bottom: 20px;
      .list-title {
        margin-bottom: 0px;
      }
      .tip {
        font-size: 13px;
        color: #909399;
      }
    }

    .list-title {
      width: auto;
      padding: 10px 20px;
      border-left: none;
      border-radius: 10px;
      background-image: linear-gradient(270deg, #70bbf8 2%, #9afb7f 100%);
      color: #fff;
      font-size: 16px;
      font-weight: bold;
    }
  }
}

.handle-btn {
  flex-shrink: 0;
  width: calc(100% - 30px);
  padding: 10px 15px;
  border-radius: 50px;
  background-color: #fff;
  text-align: center;
  color: #425afe;
  cursor: pointer;
}

.handle-btn-box {
  display: flex;
  justify-content: space-between;

  .handle-btn {
    width: 35%;

    &:first-child {
      color: #909399;
    }
  }
}
</style>
